const jsonfile = require('jsonfile');
const moment = require('moment');
const {isNumber,flatten,difference,concat,uniq,sortBy,omit,pick}= require('loadsh');
const md5 = require('md5-node');
const path=require('path')
const fs=require('fs')
const {setNotify,getNotify,readNotify}=require('../util/notify')
const {superUser,constantMenu,superCode,salt,userLimit} =require('../bin/config')
function setAuthorization(username,password){
    return username+'-'+md5(username+salt(password)+password)
}
const {setLog}=require('../util/log')
module.exports = {
    '/':(req, res)=>{
        let {cache,username=''}=req.query
        if(cache){
            const {authorization} = req.headers;
            username=username || authorization.split('-')[0]
            const socketInfo=pick(global.socketInfo,Object.keys(global.socketInfo || {}).filter(i=>i===username || !global.userList.includes(i)))
            return res.send({
                code:0,
                data:{
                    userList:global.userList,
                    socketList:global.socketList || [],
                    socketInfo,
                },
                msg:'请求成功'
            });
        }
        const users=jsonfile.readFileSync(`data/user.json`)
        const result=Object.values(users).filter(i=>i.username.includes(username))
        res.send({
            code:0,
            data:result,
            msg:'请求成功'
        });
    },
    '/readMsg':(req, res)=>{
        const {unreadCount,senduser,msg}=req.body
        if(!isNumber(unreadCount) || !senduser) return res.send({code: 1,msg: '未读数量和用户不能为空'})
        const handleObj=global.socketInfo && global.socketInfo[senduser]
        if(handleObj){
            handleObj.unreadCount=unreadCount
            handleObj.msg=msg
        }
        res.send({
            code:0,
            data:handleObj || {},
            msg:'操作成功'
        });
    },
    '/resetData':(req, res)=>{
        const {authorization} = req.headers;
        const username=authorization.split('-')[0]
        if(superUser.includes(username)){
            //清除数据接口
            res.send({
                code: 0,
                msg: '清除数据成功',
            })
        }else {
            res.send({
                code: 1,
                msg: '操作失败',
            })
        }
    },
    '/readNotify':(req, res)=>{
        const {info}=req.body
        if(!info) return res.send({code: 1,msg: 'info不能为空'})
        const {authorization} = req.headers;
        const username=authorization.split('-')[0]
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        const result=readNotify(info,username,create_time)
        //写入变量
        res.send(result || {
            code: 0,
            msg: '操作成功',
        })
    },
    '/getNote': (req, res) => {
        const {username}=req.query
        if(!username) return res.send({code: 1,msg: '用户名不能为空'})
        const users=jsonfile.readFileSync(`data/user.json`)
        res.send({
            code: 0,
            data: users[username].diary,
            msg: '请求成功'
        });
    },
    '/setNote': (req, res) => {
        const {username, content} = req.body
        if(!username || !content) return res.send({code: 1,msg: '用户名和日记内容不能为空'})
        const users=jsonfile.readFileSync(`data/user.json`)
        users[username].diary=content
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({
            code: 0,
            msg: '保存成功'
        });
    },
    '/setNotify': (req, res) => {
        const {info,username,senduser,msg} = req.body
        if(!info || !username || !senduser.length || !msg) return  res.send({code: 1,msg: '用户、标题和内容不能为空'})
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        setNotify(`${create_time} ${info}`,
            msg,
            senduser.map(username=>({username})),
            username)
        res.send({
            code: 0,
            msg: '新增成功'
        });
    },
    '/delNotify': (req, res) => {
        const {info,username} = req.query
        if(!info || !username) return res.send({code: 1,msg: '用户名和标题不能为空'})
        const notifyList=jsonfile.readFileSync(`data/notify.json`)
        if(!notifyList[info]) return res.send({code: 1,msg: '未找到相关通知'})
        if(!notifyList[info].origin) return res.send({code: 1,msg: '禁止删除系统通知'})
        delete notifyList[info]
        const index=global.notifyList.findIndex(i=>i.info===info)
        if(index>-1){
            global.notifyList.splice(index,1)
        }
        jsonfile.writeFileSync(`data/notify.json`,notifyList)
        res.send({
            code: 0,
            msg: '删除成功'
        });
    },
    '/notify': (req, res) => {
        const {username = '', create_time=''} = req.query
        const result=getNotify(username)
        res.send({
            code: 0,
            data: result.filter(i=>i.info.includes(create_time)),
            msg: '请求成功'
        });
    },
    '/info':(req, res)=>{
        //ip异常退出登录
        let data={},orderStatus={},selfNotifyList=[];
        if(!global.notifyList){
            global.notifyList=getNotify()
        }
        const {authorization} = req.headers;
        const username=authorization.split('-')[0]
        //多条未读取的用户,有读取时间不展示,有就过滤掉,true展示
        selfNotifyList=global.notifyList.filter(info=>{
            return info.readInfo.find(i => i.username === username && !i.create_time)
        })
        Object.keys(global.orderStatus).map(k=>{
            orderStatus[k]=global.orderStatus[k] && global.orderStatus[k].startTime
        })
        data.orderStatus=orderStatus
        data.notifyList=selfNotifyList
        res.send({
            code:0,
            data,
            msg:'请求成功'
        });
    },
    '/changePassword':(req, res)=>{
        const userObject=jsonfile.readFileSync(`data/user.json`)
        const {oldPassword,password,username}=req.body
        if(userObject[username]){
            if(userObject[username].password!==oldPassword){
                return res.send({
                    code: 1,
                    msg: '旧密码错误',
                })
            }else {
                const index=global.authorizationList.findIndex(i=>i.indexOf(`${username}-`)>-1)
                userObject[username].password=password
                const authorization=setAuthorization(username,password)
                userObject[username].authorization=authorization
                global.authorizationList.splice(index,1,authorization)
                jsonfile.writeFileSync(`data/user.json`, userObject)
                res.send({
                    code: 0,
                    msg: '密码修改成功',
                })
            }
        }else {
            res.send({
                code: 1,
                msg: '用户不存在',
            })
        }
    },
    '/addBalance':(req, res)=>{
        let {senduser,balance,remark,username}=req.body
        if(!senduser || !Number(balance)) return res.send({code:1,msg:'用户名和金额不能为空'});
        const today = moment().format('YYYY_MM_DD');
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        //读取今日记录
        let listObject={};
        try {
            listObject=jsonfile.readFileSync(`data/order/${today}.json`)
        }catch {}
        const userObject=jsonfile.readFileSync(`data/user.json`)
        //充值记录写入
        let log=`${create_time}，${username}为${senduser}充值余额 ${balance}`
        if(listObject[senduser]){
            if(listObject[senduser].balanceInfo){
                //只保留最近30条记录
                listObject[senduser].balanceInfo.unshift({remark,log,balance,create_time})
            }else {
                listObject[senduser]={...listObject[senduser],balanceInfo:[{remark,log,balance,create_time}]}
            }
            //已经有订单信息，chargeType 0、原来的余额+充值 1、重置的
            listObject[senduser].balance = listObject[senduser].balance + balance
        }else{
            listObject[senduser]={balanceInfo:[{remark,log,balance,create_time}]}
        }
        /*const orderTogether=flatten(Object.values(listObject).map(i=>i.senduser).filter(i=>i))
        if(orderTogether.includes(senduser)){
            listObject[senduser].username=senduser
        }*/
        listObject[senduser].username=senduser
        userObject[senduser].balance=(userObject[senduser].balance || 0)+balance
        jsonfile.writeFileSync(`data/user.json`, userObject)
        setNotify(`${create_time} ${senduser}`,
            `<p class="notifyContent">${username}为${senduser}充值余额 ${balance}${remark && `（${remark}）`}</br>充值后你的余额为${userObject[senduser].balance}</p>`,
            [{username:senduser}])
        jsonfile.writeFileSync(`data/order/${today}.json`,listObject)
        res.send({
            code: 0,
            msg: '重置余额成功',
        })
    },
    '/delBalance':(req, res)=>{
        let {senduser,balance,remark,username}=req.body
        if(!senduser) return res.send({code:1,msg:'用户名不能为空'});
        const today = moment().format('YYYY_MM_DD');
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        //读取今日记录
        const userObject=jsonfile.readFileSync(`data/user.json`)
        let listObject={};
        try {
            listObject=jsonfile.readFileSync(`data/order/${today}.json`)
        }catch {}
        //充值记录写入
        let log=`${create_time}，${username}为你重置余额为 ${balance}`
        if(listObject[senduser]){
            if(listObject[senduser].balanceInfo){
                listObject[senduser].balanceInfo.unshift({remark,log,balance,create_time})
            }else {
                listObject[senduser]={...listObject[senduser],balanceInfo:[{remark,log,balance,create_time}]}
            }
            //已经有订单信息，chargeType 0、原来的余额+充值 1、重置的
            listObject[senduser].balance=balance
        }else{
            listObject[senduser]={balanceInfo:[{remark,log,balance,create_time}]}
        }
        /*const orderTogether=flatten(Object.values(listObject).map(i=>i.senduser).filter(i=>i))
        if(orderTogether.includes(senduser)){
            listObject[senduser].username=senduser
        }*/
        listObject[senduser].username=senduser
        userObject[senduser].balance=balance
        jsonfile.writeFileSync(`data/user.json`, userObject)
        setNotify(`${create_time} ${senduser}`,
            `<p class="notifyContent">${username}为你重置余额为 ${balance}${remark && `（${remark}）`}</br>重置后你的余额为 ${userObject[senduser].balance}</p>`,
            [{username:senduser}])
        jsonfile.writeFileSync(`data/order/${today}.json`,listObject)
        res.send({
            code: 0,
            msg: '重置余额成功',
        })
    },
    '/set':(req, res)=>{
        let {senduser,password,balance,remark,username}=req.body
        if(!senduser || !username) return res.send({code:1,msg:'用户名不能为空'});
        if(senduser===username || superUser.includes(senduser) && username!==senduser){
            return res.send({code:1,msg:'操作不允许'});
        }
        const userObject=jsonfile.readFileSync(`data/user.json`)
        const newPassword=password || userObject.password || `${senduser}123456.`
        if(password){
            //修改密码
            const authorization=setAuthorization(senduser,password)
            userObject[senduser].authorization=authorization
        }
        userObject[senduser]={username:senduser,balance:0,authBtn:[],authMenuTitle:constantMenu,password:newPassword}
        //变量消失问题
        if(!global.userList){
            global.userList=[senduser]
        }else {
            if(!global.userList.includes(senduser)){
                global.userList.push(senduser)
            }
        }
        jsonfile.writeFileSync(`data/user.json`, userObject)
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/getAuth':(req, res)=>{
        const {senduser,username}=req.query
        if(!senduser || !username) return res.send({
            code: 1,
            msg: '用户名不能为空',
        });
        res.send({
            code: 0,
            data:{
                authBtn:global.authBtnList[senduser],
                authMenuTitle:global.authMenuList[senduser],
            },
            msg:'请求成功'
        })
    },
    '/setAuth':(req, res)=>{
        const {senduser,auth,authMenu,username}=req.body
        if(!senduser || !auth || !authMenu || !username) return res.send({
            code: 1,
            msg: '用户名和授权菜单不能为空',
        });
        const users=jsonfile.readFileSync(`data/user.json`)
        const currentAuth=difference(global.authBtnList[senduser],auth[1])
        global.authBtnList[senduser]=concat(currentAuth,auth[0])
        users[senduser].authBtn=global.authBtnList[senduser] || [];
        const authBtn=users[senduser].authBtn
        if(superUser.includes(senduser)){
            //authBtn授权
            const superAuthBtn=["/user/setAuth","/user/getAuth"]
            const hasSuperAuthBtn=superAuthBtn.some(auth=>authBtn.includes(auth))
            if(!hasSuperAuthBtn){
                global.authBtnList[senduser]=uniq(concat(global.authBtnList[senduser],superAuthBtn))
                users[senduser].authBtn=global.authBtnList[senduser]
            }
            //只加不减
            global.authMenuList[senduser]=uniq(concat(authMenu,global.authMenuList[senduser]))
        }else {
            //菜单权限
            const commonAuthMenu=uniq(concat(constantMenu,authMenu))
            const addMenuTitle=difference(commonAuthMenu,global.authMenuList[senduser])
            const deleteMenuTitle=difference(global.authMenuList[senduser],commonAuthMenu)
            const currentMenuTitle=difference(global.authMenuList[senduser],deleteMenuTitle)
            global.authMenuList[senduser]=concat(currentMenuTitle,addMenuTitle)
        }
        users[senduser].authMenuTitle=global.authMenuList[senduser]
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({
            code: 0,
            data:{
                authBtn:global.authBtnList[senduser],
                authMenuTitle:global.authMenuList[senduser],
            },
            msg: '授权成功',
        })
    },
    '/ipConfirm':(req, res)=>{
        const {status,senduser}=req.body
        if(!status || !senduser) return res.send({code: 1,msg:'用户名和审核状态不能为空'});
        const users=jsonfile.readFileSync(`data/user.json`)
        if(users[senduser] && users[senduser].clientIp){
            //通过为1
            if(status){
                users[senduser].lastLoginIp=users[senduser].loginIp
                users[senduser].loginIp=users[senduser].clientIp
                delete users[senduser].clientIp
            }else {
                delete users[senduser].clientIp
            }
        }else{
            return res.send({
                code: 0,
                msg: 'IP正常',
            })
        }
        jsonfile.writeFileSync(`data/user.json`,users)
        return res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/menuStar':(req, res)=>{
        //type 1展示,0隐藏
        const {code,username,platform}=req.body
        if(!username || !platform || !code) return res.send({code: 1,msg:'平台用户名和操作菜单不能为空'});
        const users=jsonfile.readFileSync(`data/user.json`)
        const starOrderMenus=users[username].starOrderMenus || {};
        let index;
        if(starOrderMenus[platform]){
            //取反操作
            index=starOrderMenus[platform].findIndex(i=>i===code)
            if(index>-1){
                starOrderMenus[platform].splice(index,1)
            }else {
                starOrderMenus[platform].push(code)
            }
        }else {
            index=-1;
            starOrderMenus[platform]=[code]
        }
        users[username].starOrderMenus=starOrderMenus
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({
            code: 0,
            data:starOrderMenus,
            msg: index>-1?'取消收藏':'收藏成功',
        })
    },
    '/chatInfo':(req, res)=>{
        const {senduser,create_time,username}=req.body
        if(!username || !create_time) return res.send({code: 1,msg:'用户名和查询时间不能为空'});
        let socketList={}
        try {
            socketList=jsonfile.readFileSync(`data/socket/${create_time}.json`)
        }catch {}
        //群组消息
        //给senduser的对话,所有人的对话
        const chatToOtherInfo=(
                senduser?(socketList[senduser] || []).filter(i=>i.from===senduser)
                :flatten(Object.values(socketList)).filter(i=>i.from===username)
            ).map(i=>{
                i.className='message-right'
                return i
            });
        //给username的对话，和其他人对话
        const chatToSelfInfo=(
            senduser?(socketList[username] || []).filter(i=>i.to===senduser)
            :(socketList[username] || [])
        ).map(i=>{
            i.className='message-left'
            return i
        });
        const groupChat=(socketList['groupChat'] || []).map(i=>{
            if(i.from!==username){
                i.className='message-left'
            }else {
                i.className='message-right'
            }
            return i
        });
        const result=senduser?sortBy(concat(chatToSelfInfo,chatToOtherInfo),'create_time'):[chatToSelfInfo,chatToOtherInfo];
        res.send({
            code: 0,
            data:{
                chat:result,
                groupChat,
            },
            msg: '请求成功',
        })
    },
    '/upload':(req, res)=>{
        const {authorization} = req.headers;
        const username=authorization.split('-')[0]
        const time = moment().format('YYYYMMDDHHmmss');
        const extname = path.extname(req.file.originalname)
        const filepath = req.file.path
        const filename = `${username}_theme${extname}`
        fs.rename(filepath,path.join(path.dirname(filepath),filename), err =>{
            if(!err){
                const imgUrl='/assets/upload/user/'+filename
                res.send({code:0,data:imgUrl,msg:'上传成功'});
            }else {
                res.send({code:1,msg:'上传失败'});
            }
        })
    },
    '/design':(req, res)=>{
        const {themeImg,username}=req.body
        const users=jsonfile.readFileSync(`data/user.json`)
        users[username].themeImg=themeImg
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({code:0,msg:'保存成功'});
    },
    '/menuStatus':(req, res)=>{
        //type 1展示,0隐藏
        const {item,username,platform}=req.body
        if(!username || !platform || !item) return res.send({code: 1,msg:'平台用户名和操作菜单不能为空'});
        const users=jsonfile.readFileSync(`data/user.json`)
        const hideOrderMenus=users[username].hideOrderMenus || {}
        item.platform=platform
        if(hideOrderMenus[platform]){
            //取反操作
            const index=hideOrderMenus[platform].findIndex(i=>i.code===item.code)
            if(index>-1){
                hideOrderMenus[platform].splice(index,1)
            }else {
                hideOrderMenus[platform].push(item)
            }
        }else {
            hideOrderMenus[platform]=[item]
        }
        users[username].hideOrderMenus=hideOrderMenus
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({
            code: 0,
            data:hideOrderMenus,
            msg: '操作成功',
        })
    },
    '/login':(req, res)=>{
        const {username,password,code}=req.body
        const clientIp=req.ip.match(/\d+\.\d+\.\d+\.\d+/)[0]
        let users={}
        try {
            users=jsonfile.readFileSync(`data/user.json`)
        }catch {
            jsonfile.writeFileSync(`data/user.json`,{})
        }
        if(users[username]){
            //第一次登录记录
            const loginIp=users[username].loginIp
            //最终入口
            if(loginIp && clientIp!==loginIp){
                //记录ip
                if(superUser.includes(username) && superCode===code){
                    delete users[username].clientIp
                }else {
                    users[username].clientIp=clientIp
                    jsonfile.writeFileSync(`data/user.json`,users)
                    return res.send({
                        code: 1,
                        msg: '登录IP异常，请联系管理员确认',
                    })
                }
            }
            if(users[username].password!==password){
                return  res.send({
                    code: 1,
                    msg: '密码错误',
                })
            }
        }else {
            return res.send({
                code: 1,
                msg: '用户不存在',
            })
        }
        const authorization=setAuthorization(username,password)
        const data={authorization,username,balance:users[username].balance}
        //authorization,loginIp赋值
        users[username].authorization=data.authorization
        users[username].loginIp=clientIp
        if(!global.authorizationList.includes(data.authorization)){
            global.authorizationList.push(data.authorization)
        }

        const {asyncMenu}=jsonfile.readFileSync(`data/menu.json`)
        //隐藏菜单
        data.hideOrderMenus=users[username].hideOrderMenus
        data.starOrderMenus=users[username].starOrderMenus
        let authList={},authBtn=users[username].authBtn || [],authMenuTitle=users[username].authMenuTitle || [];
        if(superUser.includes(username)){
            const superAuthBtn=["/user/setAuth","/user/getAuth"]
            const hasSuperAuthBtn=superAuthBtn.some(auth=>authBtn.includes(auth))
            if(!hasSuperAuthBtn){
                authBtn=uniq(concat(authBtn,superAuthBtn))
                users[username].authBtn=authBtn
            }
            if(!authMenuTitle.length){
                authMenuTitle=asyncMenu.map(item=>item.meta.title)
                users[username].authMenuTitle=authMenuTitle
            }
            // flatten()
            data.isSuper=1
            data.asyncMenu=asyncMenu
            data.authMenuTitle=asyncMenu.map(item=>item.meta.title)
        }else {
            const allHideTitle=asyncMenu.filter(i=>i.meta.hide && constantMenu.includes(i.meta.title)).map(i=>i.meta.title);
            const userHideTitle=asyncMenu.filter(i=>i.meta.hide && authMenuTitle.includes(i.meta.title)).map(i=>i.meta.title);
            const addHideTitle=difference(allHideTitle,userHideTitle);
            // 更默认新授权菜单
            if(addHideTitle.length){
                authMenuTitle=concat(authMenuTitle,addHideTitle);
                users[username].authMenuTitle=authMenuTitle;
            }
            data.asyncMenu=asyncMenu.filter(i=>authMenuTitle.includes(i.meta.title))
            data.authMenuTitle=authMenuTitle
        }
        asyncMenu.map(item=>{
            if(!item.meta.hide){
                authList[item.meta.title]= (item.meta.authBtn || []).map(auth=>({name:auth.split(":")[0],auth:auth.split(":")[1],module:item.meta.title}))
            }
        })
        global.authBtnList[username]=authBtn
        data.authList=authList
        data.authBtn=authBtn
        data.themeImg=users[username].themeImg
        jsonfile.writeFileSync(`data/user.json`,users)
        res.send({
            code: 0,
            data,
            msg: '登录成功',
        })
    },
    '/del':(req, res)=>{
        const {username,senduser}=req.body
        if(!username || !senduser) return res.send({code:1,msg:'用户名不能为空'});
        const userObject=jsonfile.readFileSync(`data/user.json`)
        if(userObject[senduser]){
            if(superUser.includes(senduser) || senduser===username){
                return  res.send({
                    code: 1,
                    msg: '该用户不可删除',
                })
            }
            delete userObject[senduser]
            global.userList=difference(global.userList,[senduser])
            jsonfile.writeFileSync(`data/user.json`,userObject)
            res.send({
                code: 0,
                msg: '删除成功',
            })
        }else {
            res.send({
                code: 1,
                msg: '用户不存在',
            })
        }
    },
}
